//HT1622驱动段码屏，COM8 * SEG32
//44 LQFP-A(市场上有盗版的HT1622,需要注意)
//写模式: 占空比 50%, 时钟频率: 4~150KHz, 取 ((150+4)/2)KHz左右的频率
//77KHz,得出H占空比时间:12.9us,取12us,对频率: 83.3KHz
//运行环境: 多任务
//为避免被多任务打断数据传输,数据传输必须在最高级的任务执行


#include "HT162X.h"
#include "HT162X_Pin.h"
#include "HT162X_Parts_Num.h"



#define HT_Cmd_Sys_ON 0B00000001
#define HT_Cmd_LCD_ON 0B00000011
#define HT_Cmd_RC32K_ON 0B00011000


HT162X_Device_S HT_Device;

#define HT_RAM_Length 16 //Seg0-Seg15,Com0-Com7
uint8_t HT_RAM[HT_RAM_Length];


void HT162X_Delay(unsigned char n)
{
    while(n--)
    {
        asm("nop");
    }
}

void HT_RAM_Setting(Cad_Dat_S Cad_Dat)
{
    if(Cad_Dat.Cad_Pin >= HT_RAM_Length) return;

    if(Cad_Dat.Cad_Dis == Char_ON) HT_RAM[Cad_Dat.Cad_Pin] |= Cad_Dat.Cad_Com;
    else HT_RAM[Cad_Dat.Cad_Pin] &= (~Cad_Dat.Cad_Com);
}

//写数据,低4位有效,自低往高写位
void HT162X_W_Bit(uint16_t ht,uint8_t bitNum)
{
    uint8_t i;
    uint16_t temp_Bit;

    if(bitNum == 0) temp_Bit = 1;
    else temp_Bit = (0x1 << (bitNum - 1));
    for (i = 0; i < bitNum; i++)
    {
        HT_Device.HT_Data_Handled(((ht & temp_Bit) == temp_Bit)?1:0);
        HT_Device.HT_WR_Handled(0);
        HT162X_Delay(2);
        HT_Device.HT_WR_Handled(1);
        HT162X_Delay(1);
        ht <<= 1;
    }
}
void HT162X_ResetRAM(void)
{
    uint8_t i;

    //注意: 连续命令,ID只需要开头发一次
    for (i = 0; i < HT_RAM_Length; i++)
    {
        HT_RAM[i] = 0x00;
    }
}
void HT162X_WriteAll(void)
{
    uint32_t i;
   
    HT_Device.HT_CS_Handled(0);
    HT162X_Delay(3);
    HT162X_W_Bit(0b101,3); //Write ID 101
    HT162X_W_Bit(0,6); //address
    for (i = 0; i < HT_RAM_Length; i++)
    {
        HT162X_W_Bit(HT_RAM[i],8);
    }
    HT_Device.HT_CS_Handled(1);
}
void HT162X_Init(void)
{
    HT162X_PinConfig();
    HT_Device.HT_CS_Handled = HT162X_CS_Handled;
    HT_Device.HT_WR_Handled = HT162X_WR_Handled;
    HT_Device.HT_RD_Handled = HT162X_RD_Handled;
    HT_Device.HT_Data_Handled = HT162X_Data_Handled;
    
    HT_Device.HT_CS_Handled(0);
    HT162X_Delay(3);
    HT162X_W_Bit(0b100,3); //Write Cmd 100
    HT162X_W_Bit((HT_Cmd_RC32K_ON << 1),9);
    HT162X_W_Bit((HT_Cmd_Sys_ON << 1),9);
    HT162X_W_Bit((HT_Cmd_LCD_ON << 1),9);
    HT_Device.HT_CS_Handled(1);
    HT162X_ResetRAM();
    HT162X_WriteAll(); 
}

void HT162X_Write(HT_Data_S ht)
{
    HT_Device.HT_CS_Handled(0);
    HT162X_Delay(3);
    HT162X_W_Bit(0b101,3); //Write ID 101
    HT162X_W_Bit(ht.address,6);
    HT162X_W_Bit(ht.data,8);
    HT_Device.HT_CS_Handled(1);
}
void HT162X_RAM_Tx(void)
{
    HT162X_WriteAll();
}

void HT162X_Reset(void)
{
    HT162X_ResetRAM();
    HT162X_WriteAll();   
}
